package org.LowAltitudeEconomy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.LowAltitudeEconomy.mapper.SensorMapper;
import org.LowAltitudeEconomy.pojo.Sensor;
import org.LowAltitudeEconomy.service.SensorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.*;

import static com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery;

@Service
public class SensorServiceImpl implements SensorService {
    @Autowired
    private SensorMapper sensorMapper;

    @Override
    //添加新的传感器
    public void addSensor(String deviceSn, String longitude, String latitude, Integer userId) {
        Sensor sensor = new Sensor();
        sensor.setDeviceSn(deviceSn);
        sensor.setLongitude(longitude);
        sensor.setLatitude(latitude);
        sensor.setUserId(userId);
        try {
            sensorMapper.insert(sensor);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("传感器添加失败");
        }
    }

    //匹配传感器id (为其他功能做铺垫)
    @Override
    public Sensor findSensorById(Integer sensorId) {
        Sensor sensor = sensorMapper.selectOne(new LambdaQueryWrapper<Sensor>().eq(Sensor::getSensorId, sensorId));
        if (sensor == null) {
            return null;
        } else {
            return sensor;
        }
    }

    //判断传感器的序列号是否存在
    public boolean existsByDeviceSn(String deviceSn) {
        return sensorMapper.exists(
                new LambdaQueryWrapper<Sensor>()
                        .eq(Sensor::getDeviceSn, deviceSn)
        );
    }


    //获取特定传感器的信息（传入设备序列号和用户id）
    @Override
    public Page<Sensor> getSensorByDeviceSnAndUserId(String deviceSn, Integer userId, Page<Object> objectPage){
        Page<Sensor> page = new Page<>(objectPage.getCurrent(), objectPage.getSize());
        //MyBatis-Plus的 Lambda条件构造器
        LambdaQueryWrapper<Sensor> queryWrapper = lambdaQuery();
        if (deviceSn!= null) {
            queryWrapper.eq(Sensor::getDeviceSn, deviceSn);
        }
        if (userId!= null) {
            queryWrapper.eq(Sensor::getUserId, userId);
        }
        return sensorMapper.selectPage(page, queryWrapper);
    }


    //获取所有传感器的信息
    @Override
    public Page<Sensor> getAllSensors(Page<Object> objectPage){
        return sensorMapper.selectPage(new Page<>(objectPage.getCurrent(), objectPage.getSize()), null);
    }

}
